import axios from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router'
const baseURL = '/api'

const instance = axios.create({
  baseURL,
  timeout: 5000,
  withCredentials: true
})
// 请求拦截
instance.interceptors.request.use(
  (config) => {
    //携带token
    const token = useUserStore().token
    if (token) {
      config.headers.Authorization = token
    }
    if (config.url.includes('/fd')) {
      config.url = config.url.replace(/^\/fd/, '')
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers['Content-Type'] = 'application/json'
    }
    //

    //
    return config
  },
  (err) => Promise.reject(err)
)
// 响应拦截
instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 0) {
      if (res.config.url == '/person/resetpw') {
        return res.data
      }
      return res.data.data
    }
    ///
    if (res.headers.get('Content-Type') == 'application/pdf') {
      return res.data
    }
    ElMessage.error({ message: `${res.data.msg || '服务异常'}`, offset: 70 })
    return Promise.reject(res.data)
  },
  (err) => {
    if (err.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error({ message: `${err.response?.data?.msg || '服务异常'}`, offset: 70 })
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
